package com.xdu.yunwufog.connection.utils;

import com.xdu.yunwufog.connection.netty.ChannelTaskThread;
import io.netty.util.concurrent.SingleThreadEventExecutor;
import io.netty.util.internal.SystemPropertyUtil;

import java.net.InetSocketAddress;
import java.util.concurrent.*;

/**
 * 多线程任务池，每个线程从连接池获取连接
 */
public class NettyTaskPool {
    private static final int CORE_POLL_SIZE ;
    private static final int MAX_POLL_SIZE;
    static {
        CORE_POLL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
        MAX_POLL_SIZE = Runtime.getRuntime().availableProcessors()*8;
    }
    private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            CORE_POLL_SIZE,
            MAX_POLL_SIZE,
            3,
            TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1024),
            new ThreadPoolExecutor.DiscardOldestPolicy()
    );


    public static String submitTask(String message, InetSocketAddress socketAddress) throws Exception{
        // 单个任务在线程池内分配单个线程，用于同步等待封装的返回结果
        Future<String> submit = threadPool.submit(new ChannelTaskThread(message,socketAddress));
        // Future.get() 获取任务的结果，若存在异常，则抛出ExecutionException
        String response = submit.get();

        return response;
    }
}
